// src/routes/securities/+page.ts
import type { PageLoad } from './$types';
import { sampleStocks } from './sampleData';

const genTransactions = () => {
    const transactions = [];

    for (let i = 1; i <= 300; i++) {
        var type = i % 3 == 0 ? "买入" : "卖出";
        transactions.push({
            id: i,
            quantity: Math.floor(Math.random() * 1000) + 1, // Random quantity between 1 and 1000
            type: type,
            price: (Math.random() * 100).toFixed(2), // Random price between 0.00 and 99.99
            date: new Date().toISOString().slice(0, 10), // Current date (or use a random past date if desired)
        });
    }

    return transactions;
};

export const load: PageLoad = async ({ fetch, params }) => {

    var transactions = genTransactions();
    try {


        const res = await fetch(`/api/stocks`, {
            method: 'GET',
            // If needed, you can include headers, such as authorization tokens
            // headers: {
            //   'Authorization': 'Bearer your_token_here',
            // },
        });

        if (!res.ok) {
            // If the response status is not OK, throw an error
            throw new Error(`(positions/+page.ts)Server returned an error: ${res.status}`);
        }

        const stocks = await res.json();
        // If the server response is empty, return sample data
        if (!stocks || stocks.length === 0) {
            return {
                stocks: sampleStocks,
                transactions: transactions!
            };
        }

        return { stocks };
    } catch (error) {
        // If there's any error (e.g., network issue), return sample data
        console.error('Error fetching stocks:', error);
        return {
            stocks: sampleStocks,
            transactions: transactions!
        };
    }
};